package ren.xxpure.service.impl;

import cn.hutool.jwt.JWTUtil;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import ren.xxpure.dao.TokenRepository;
import ren.xxpure.dao.UserRepository;
import ren.xxpure.entity.CommonResult;
import ren.xxpure.entity.LoginUser;
import ren.xxpure.entity.Token;
import ren.xxpure.entity.User;
import ren.xxpure.service.UserService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {
	public static final String SECRET = "aklsjlkdj;k.//.askd;lja";
	@Resource
	UserRepository userRepository;
	@Resource
	AuthenticationManager authenticationManager;
	@Resource
	TokenRepository tokenRepository;
	@Resource
	BCryptPasswordEncoder bCryptPasswordEncoder;

	@Override
	public CommonResult<String> login(String userName, String password) {
		UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userName, password);
		Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);

		if (Objects.isNull(authenticate)) {
			throw new RuntimeException("用户名或密码错误");
		}
		LoginUser principal = (LoginUser) authenticate.getPrincipal();
		Map<String, Object> map = new HashMap<String, Object>() {
			private static final long serialVersionUID = 1L;

			{
				put("uid", principal.getUser().getId());
				put("expire_time", System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 15);
			}
		};
		Token token = new Token(null, JWTUtil.createToken(map, SECRET.getBytes()),
				principal.getUser().getId(), principal);
		Token temp = tokenRepository.findByUid(principal.getUser().getId());
		if (temp != null) {
			tokenRepository.delete(temp);
		}
		Token save = this.tokenRepository.save(token);
		return new CommonResult<>(200, "登录成功", save.getToken());
	}

	@Override
	public CommonResult<String> logout() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		LoginUser principal = (LoginUser) authentication.getPrincipal();
		String id = principal.getUser().getId();
		Token token = this.tokenRepository.removeTokenByUid(id);
		return new CommonResult<>(HttpStatus.OK.value(), "登出成功", token.getUid());
	}

	@Override
	public CommonResult<User> register(User user) {
		if (this.userRepository.findUserByUserName(user.getUserName()) != null) {
			return new CommonResult<>(HttpStatus.BAD_REQUEST.value(), "用户名已存在");
		}
		user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
		User save = this.userRepository.save(user);
		save.setPassword(null);
		return new CommonResult<>(HttpStatus.OK.value(), "注册成功", save);
	}

	@Override
	public CommonResult<User> info() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		LoginUser principal = (LoginUser) authentication.getPrincipal();
		User user = principal.getUser();
		user.setPassword(null);
		return new CommonResult<>(HttpStatus.OK.value(), "获取用户信息成功", user);
	}

	@Override
	public CommonResult<String> update(User user) {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		LoginUser principal = (LoginUser) authentication.getPrincipal();
		if (!user.getId().equals(principal.getUser().getId())) {
			return new CommonResult<>(HttpStatus.BAD_REQUEST.value(), "更新失败，用户id不匹配");
		} else {
			user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
			User save = this.userRepository.save(user);
			save.setPassword(null);
			return new CommonResult<>(HttpStatus.OK.value(), "更新成功");
		}
	}

}
